/**
 * 导航菜单组件
 * 支持路由切换和状态管理
 */

class NavigationComponents {
    constructor() {
        this.currentPath = window.location.hash.slice(1) || '/';
        this.sidebarMenu = [];
        this.isSidebarCollapsed = false;
    }
    
    /**
     * 初始化导航组件
     */
    init() {
        this.loadMenuData();
        this.renderSidebar();
        this.renderHeader();
        this.renderFooter();
        this.bindEvents();
        this.updateActiveState();
    }
    
    /**
     * 加载菜单数据
     */
    loadMenuData() {
        if (window.RouteConfig && window.RouteConfig.getSidebarMenu) {
            this.sidebarMenu = window.RouteConfig.getSidebarMenu();
        } else {
            // 默认菜单数据
            this.sidebarMenu = [
                {
                    title: '系统管理',
                    icon: 'layui-icon-set',
                    children: [
                        { path: '/', title: '首页', icon: 'layui-icon-home' },
                        { path: '/charts', title: '图表测试', icon: 'layui-icon-chart' }
                    ]
                },
                {
                    title: '数据统计',
                    icon: 'layui-icon-chart-screen',
                    children: [
                        { path: '/stats/day', title: '按天统计', icon: 'layui-icon-chart-screen' },
                        { path: '/stats/proc', title: '按进程统计', icon: 'layui-icon-chart-screen' }
                    ]
                },
                {
                    title: '链接管理',
                    icon: 'layui-icon-link',
                    children: [
                        { path: '/links', title: '链接信息', icon: 'layui-icon-link' }
                    ]
                },
                {
                    title: '工具箱',
                    icon: 'layui-icon-engine',
                    children: [
                        { path: '/v2/resolve', title: 'V2解析', icon: 'layui-icon-engine' }
                    ]
                }
            ];
        }
    }
    
    /**
     * 渲染侧边栏
     */
    renderSidebar() {
        const sidebar = document.querySelector('.layui-side .layui-side-scroll');
        if (!sidebar) return;
        
        let sidebarHtml = '<ul class="layui-nav layui-nav-tree" lay-filter="sidebar-nav">';
        
        this.sidebarMenu.forEach(menu => {
            if (menu.children && menu.children.length > 0) {
                sidebarHtml += `
                    <li class="layui-nav-item">
                        <a class="" href="javascript:;">
                            <i class="layui-icon ${menu.icon}"></i>
                            <span>${menu.title}</span>
                            <span class="layui-nav-more"></span>
                        </a>
                        <dl class="layui-nav-child">
                `;
                
                menu.children.forEach(child => {
                    sidebarHtml += `
                        <dd data-path="${child.path}">
                            <a href="${child.path}">
                                <i class="layui-icon ${child.icon}"></i>
                                <span>${child.title}</span>
                            </a>
                        </dd>
                    `;
                });
                
                sidebarHtml += '</dl></li>';
            } else {
                sidebarHtml += `
                    <li class="layui-nav-item" data-path="${menu.path}">
                        <a href="${menu.path}">
                            <i class="layui-icon ${menu.icon}"></i>
                            <span>${menu.title}</span>
                        </a>
                    </li>
                `;
            }
        });
        
        sidebarHtml += '</ul>';
        sidebar.innerHTML = sidebarHtml;
        
        // 初始化LayUI导航
        if (typeof layui !== 'undefined') {
            layui.use(['element'], function() {
                var element = layui.element;
                element.render('nav', 'sidebar-nav');
            });
        }
    }
    
    /**
     * 渲染头部导航
     */
    renderHeader() {
        const header = document.querySelector('.layui-header');
        if (!header) return;
        
        const headerHtml = `
            <div class="layui-logo layui-hide-xs layui-bg-black">
                <i class="layui-icon layui-icon-home"></i>
                <span>LayUI SPA</span>
            </div>
            <ul class="layui-nav layui-layout-left layui-hide-xs">
                <li class="layui-nav-item" data-path="/">
                    <a href="/">首页</a>
                </li>
                <li class="layui-nav-item" data-path="/charts">
                    <a href="/charts">图表</a>
                </li>
                <li class="layui-nav-item" data-path="/links">
                    <a href="/links">链接</a>
                </li>
                <li class="layui-nav-item">
                    <a href="javascript:;">统计
                        <span class="layui-nav-more"></span>
                    </a>
                    <dl class="layui-nav-child">
                        <dd data-path="/stats/day">
                            <a href="/stats/day">按天统计</a>
                        </dd>
                        <dd data-path="/stats/proc">
                            <a href="/stats/proc">按进程统计</a>
                        </dd>
                    </dl>
                </li>
                <li class="layui-nav-item" data-path="/v2/resolve">
                    <a href="/v2/resolve">V2解析</a>
                </li>
            </ul>
            <ul class="layui-nav layui-layout-right">
                <!-- 用户中心功能已移除 -->
                <li class="layui-nav-item" lay-header-event="menuRight" lay-unselect>
                    <a href="javascript:;">
                        <i class="layui-icon layui-icon-more-vertical"></i>
                    </a>
                </li>
            </ul>
        `;
        
        header.innerHTML = headerHtml;
        
        // 初始化LayUI导航
        if (typeof layui !== 'undefined') {
            layui.use(['element'], function() {
                var element = layui.element;
                element.render('nav');
            });
        }
    }
    
    /**
     * 渲染底部
     */
    renderFooter() {
        const footer = document.querySelector('.layui-footer');
        if (!footer) return;
        
        const footerHtml = `
            <div class="footer-content">
                <p>&copy; 2024 LayUI单页面应用. All rights reserved.</p>
                <p>
                    <a href="javascript:;" onclick="showAbout()">关于</a> | 
                    <a href="javascript:;" onclick="showHelp()">帮助</a> | 
                    <a href="javascript:;" onclick="showContact()">联系我们</a>
                </p>
            </div>
        `;
        
        footer.innerHTML = footerHtml;
    }
    
    /**
     * 绑定事件
     */
    bindEvents() {
        const self = this;
        
        // 监听路由变化
        window.addEventListener('hashchange', () => {
            self.currentPath = window.location.hash.slice(1) || '/';
            self.updateActiveState();
        });
        
        // 监听侧边栏点击事件
        document.addEventListener('click', (e) => {
            const link = e.target.closest('a[href^="/"]');
            if (link && link.closest('.layui-side')) {
                e.preventDefault();
                const path = link.getAttribute('href');
                if (window.router) {
                    window.router.navigate(path);
                } else {
                    window.location.hash = path;
                }
            }
        });
        
        // 监听头部导航点击事件
        document.addEventListener('click', (e) => {
            const link = e.target.closest('.layui-header a[href^="/"]');
            if (link && !link.closest('.layui-nav-child')) {
                e.preventDefault();
                const path = link.getAttribute('href');
                if (window.router) {
                    window.router.navigate(path);
                } else {
                    window.location.hash = path;
                }
            }
        });
        
        // 监听移动端菜单切换
        const menuToggle = document.querySelector('.layui-header-event');
        if (menuToggle) {
            menuToggle.addEventListener('click', () => {
                self.toggleMobileMenu();
            });
        }
        
        // 监听侧边栏折叠按钮
        const sidebarToggle = document.querySelector('.layui-side-shrink');
        if (sidebarToggle) {
            sidebarToggle.addEventListener('click', () => {
                self.toggleSidebar();
            });
        }
    }
    
    /**
     * 更新激活状态
     */
    updateActiveState() {
        const path = this.currentPath;

        // 移除所有激活状态
        document.querySelectorAll('.layui-nav-item').forEach(item => {
            item.classList.remove('layui-nav-itemed', 'layui-this');
        });

        // 查找匹配的导航项
        const navItem = document.querySelector(`a[href="${path}"]`)?.closest('.layui-nav-item');
        if (navItem) {
            navItem.classList.add('layui-this');
            
            // 展开父级菜单
            const parentNav = navItem.closest('.layui-nav-child')?.closest('.layui-nav-item');
            if (parentNav) {
                parentNav.classList.add('layui-nav-itemed');
            }
            
            // 更新状态管理器
            if (window.StateManager) {
                window.StateManager.setState('ui.activeNavItem', path);
            }
        }

        // 更新页面标题
        this.updatePageTitle(path);
    }
    
    /**
     * 更新页面标题
     */
    updatePageTitle(path) {
        if (window.RouteConfig && window.RouteConfig.routeUtils) {
            const title = window.RouteConfig.routeUtils.getPageTitle(path);
            const pageTitle = title ? `${title} - LayUI单页面应用` : 'LayUI单页面应用';
            document.title = pageTitle;
            
            // 更新状态管理器
            if (window.StateManager) {
                window.StateManager.setState('app.pageTitle', pageTitle);
            }
        }
    }
    
    /**
     * 切换侧边栏折叠状态
     */
    toggleSidebar() {
        const side = document.querySelector('.layui-side');
        const body = document.body;
        
        if (window.innerWidth <= 768) {
            // 移动端：显示/隐藏遮罩
            const shade = document.querySelector('.layui-layout-shade');
            if (shade) {
                shade.remove();
            } else {
                const newShade = document.createElement('div');
                newShade.className = 'layui-layout-shade';
                newShade.onclick = () => this.toggleSidebar();
                body.appendChild(newShade);
            }
            side.classList.toggle('layui-side-show');
        } else {
            // PC端：折叠/展开
            body.classList.toggle('layui-layout-admin-hide-side');
            
            // 更新状态管理器
            if (window.StateManager) {
                const isCollapsed = body.classList.contains('layui-layout-admin-hide-side');
                window.StateManager.setState('app.sidebarCollapsed', isCollapsed);
            }
        }
    }
    
    /**
     * 切换移动端菜单
     */
    toggleMobileMenu() {
        const side = document.querySelector('.layui-side');
        const shade = document.querySelector('.layui-layout-shade');
        
        if (side.style.left === '0px') {
            side.style.left = '-200px';
            if (shade) shade.remove();
        } else {
            side.style.left = '0';
            if (!shade) {
                const shadeDiv = document.createElement('div');
                shadeDiv.className = 'layui-layout-shade';
                shadeDiv.style.cssText = 'position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,.3);z-index:998;';
                document.body.appendChild(shadeDiv);
                
                shadeDiv.addEventListener('click', () => {
                    side.style.left = '-200px';
                    shadeDiv.remove();
                });
            }
        }
    }
    
    /**
     * 显示关于对话框
     */
    showAbout() {
        layui.use(['layer'], function() {
            var layer = layui.layer;
            layer.open({
                title: '关于',
                content: 'LayUI单页面应用<br>版本: 1.0.0<br>基于 LayUI 框架开发',
                area: ['400px', '200px'],
                btn: ['确定']
            });
        });
    }
    
    /**
     * 显示帮助对话框
     */
    showHelp() {
        layui.use(['layer'], function() {
            var layer = layui.layer;
            layer.open({
                title: '帮助',
                content: '如有问题，请联系系统管理员或查看相关文档。',
                area: ['400px', '150px'],
                btn: ['确定']
            });
        });
    }
    
    /**
     * 显示联系我们对话框
     */
    showContact() {
        layui.use(['layer'], function() {
            var layer = layui.layer;
            layer.open({
                title: '联系我们',
                content: '邮箱: admin@example.com<br>电话: 123-456-7890',
                area: ['400px', '150px'],
                btn: ['确定']
            });
        });
    }
}

// 初始化导航组件
if (typeof module !== 'undefined' && module.exports) {
    module.exports = NavigationComponents;
} else {
    window.NavigationComponents = NavigationComponents;
    
    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        if (window.navigationComponents) {
            window.navigationComponents.init();
        }
    });
}